/**
 * 
 */
package edu.arizona.bio5.onto.decomposition;

import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.semanticweb.owlapi.model.OWLEntity;

import uk.ac.manchester.cs.util.SetUtils;

/**
 * Builds the term-based index based on min seed signatures in atoms labels
 * 
 * @author Pavel Klinov
 *
 */
public class MSSBasedADIndexBuilder implements ADIndexBuilder {

	@Override
	public void index(AtomicDecomposition ad) {
		Map<URI, Set<Atom>> tbIndex = new HashMap<URI, Set<Atom>>();
		
		for (Atom atom : ad.getAtoms()) {
			MSSLabel label = getMSSLabel(atom);
			Set<OWLEntity> termsAtomIsRelevantFor = (label != null && label.isComplete()) ? getTermBasedOnLabel(label) : atom.getSignature(); 
			
			for (OWLEntity term : termsAtomIsRelevantFor) {
				Set<Atom> relAtoms = tbIndex.get(term.getIRI().toURI());
				
				relAtoms = relAtoms == null ? new HashSet<Atom>() : relAtoms;
				relAtoms.add(atom);
				tbIndex.put(term.getIRI().toURI(), relAtoms);
			}
		}
		
		ad.setTermBasedIndex(tbIndex);
	}

	private MSSLabel getMSSLabel(Atom atom) {
		return (MSSLabel) atom.getLabel(MSSLabel.TYPE); 
	}
	
	protected Set<OWLEntity> getTermBasedOnLabel(MSSLabel label) {		
		return SetUtils.union(label.getSeedSignatures());
	}
}